package com.msb.smsgateway.runnable;

import com.msb.common.constart.RabbitMQConstants;
import com.msb.common.constart.SmsConstant;
import com.msb.common.enums.CMPP2ResultEnums;
import com.msb.common.model.StandardReport;
import com.msb.common.model.StandardSubmit;
import com.msb.common.util.CMPP2ResultUtil;
import com.msb.common.util.CMPPDeliverMapUtil;
import com.msb.common.util.CMPPSubmitRepoMapUtil;
import com.msb.common.util.SpringUtil;
import com.msb.smsgateway.netty4.entity.CmppSubmitResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;

/**
 * @Author: lmf
 * @Create: 2025/3/22 11:13
 * @module
 */
@Slf4j
public class SubmitRepoRunnable implements Runnable {

    private final CmppSubmitResp resp;

    private final RabbitTemplate rabbitTemplate = SpringUtil.getBeanByClass(RabbitTemplate.class);

    public SubmitRepoRunnable(CmppSubmitResp resp) {
        this.resp = resp;
    }

    @Override
    public void run() {
        StandardReport report = null;

        // 拿到自增id 获取对应存储的submit
        StandardSubmit submit = CMPPSubmitRepoMapUtil.remove(resp.getSequenceId());
        // 根据运营商返回result，确定短信状态并封装submit
        int result = resp.getResult();
        if (result != CMPP2ResultEnums.OK.getResult()) {
            //  短息发送失败
            String resultMessage = CMPP2ResultUtil.getResultMessage(result);
            submit.setReportState(SmsConstant.SEND_FAIL);
            submit.setErrorMessage(resultMessage);
        } else {
            // 短信发送成功
            report = new StandardReport();
            BeanUtils.copyProperties(submit, report);
            CMPPDeliverMapUtil.put(resp.getMsgId() + "", report);
        }

        log.info("短信发送到es：{}", submit);
        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_LOG_ES, submit);
    }
}
